﻿using System;
using System.IO;
using BaseControlLibrary;
using DBAccessLibrary.Common;
using DevControlLibrary.UI;
using DevExpress.Xpf.Docking;
using DevControlLibrary.Common;
using DevExpress.Xpf.Core;
using QueryResource.Common;
using QueryResource.ViewModel;
using Microsoft.Win32;
using System.Windows;
using DBAccessLibrary.Model;

namespace DevControlLibrary.ViewModel
{
    public class MainViewModel : BasePropertyChange
    {
        readonly DBTreeViewModel _treeViewModel;
        private int _documentCount = 1;
        public MainViewModel(DBTreeViewModel treeview)
        {
            _treeViewModel = treeview;

            CreateDBCommand = new DelegateCommand(() =>
            {
                RegistDB regist = new RegistDB();
                if (regist.ShowDialog() == true)
                {
                    this._treeViewModel.Connection();
                }
            });

            TxtFormatCommand = new DelegateCommand(() =>
            {
                LayoutPanel panel = GetActiveSqlControlPanel();
                if (panel != null)
                {
                    SQLControl control = panel.Content as SQLControl;
                    if (control != null)
                    {
                        control.ViewModel.SqlFormatPainter(control.ViewModel.SelectText, true);
                    }
                }
            }, () => {
                LayoutPanel panel = GetActiveSqlControlPanel();
                if (panel != null)
                {
                    SQLControl control = panel.Content as SQLControl;
                    if (control != null)
                    {
                        if (control.ViewModel != null)
                        {
                            return !string.IsNullOrEmpty(control.ViewModel.SelectText);
                        }
                    }
                }
                return false;
            });

            FileOpenCommand = new DelegateCommand(() => {
                OpenFileDialog dlg = new OpenFileDialog
                                         {
                                             ValidateNames = true,
                                             CheckPathExists = true,
                                             CheckFileExists = true,
                                             Filter = "文本文件 （*.txt)|*.txt|SQL 文件 (*.sql)|*.sql"
                                         };
                                                            bool? showDialog = dlg.ShowDialog();
                                                            if (showDialog != null && showDialog.Value)
                {
                    ShowNewWindowLoadFile(dlg.SafeFileName, dlg.FileName,true);
                }
            });
            FileSaveCommand = new DelegateCommand(() =>
            {
                LayoutPanel panel = GetActiveSqlControlPanel();
                if (panel != null)
                {
                    SQLControl sqlcontrol = panel.Content as SQLControl;
                    if (sqlcontrol != null)
                    {
                        if (sqlcontrol.IsNewDocument)
                        {
                            string fileName = string.Empty;
                            if (panel.Caption.ToString().IndexOf('*') > 0)
                            {
                                fileName = panel.Caption.ToString().Replace("*", "");
                                if (fileName != "文档")
                                {
                                    fileName = "Temporary\\" + fileName;
                                }
                                sqlcontrol.SaveFile(fileName);
                                panel.Caption = panel.Caption.ToString().Replace("*", "");
                            }
                        }
                        else
                        {
                            //文件
                            if (File.Exists(sqlcontrol.FilePath))
                            {
                                sqlcontrol.SaveFile(sqlcontrol.FilePath);
                                panel.Caption = panel.Caption.ToString().Replace("*", "");
                            }
                        }
                    }
                }
                else
                {
                    panel = GetActiveTableDefinitionControlPanel();
                    if (panel != null)
                    {
                        TableDefinitionControl tablecontrol = panel.Content as TableDefinitionControl;
                        if (tablecontrol != null)
                        {
                            if (tablecontrol.Save())
                            {
                                panel.Caption = panel.Caption.ToString().Replace("*", "");
                            }
                        }
                    }
                }
            },()=>
                  {
                      LayoutPanel panel = GetActiveSqlControlPanel();
                      if (panel == null)
                      {
                          panel = GetActiveTableDefinitionControlPanel();
                      }

                       if (panel != null)
                      {
                          if (panel.Caption.ToString().IndexOf('*') >= 0)
                              return true;
                      }
                      return false;
                  });
            FileSaveAsCommand = new DelegateCommand(() =>
            {
                SaveFileDialog dlg = new SaveFileDialog
                                         {
                                             Filter = "文本文件 （*.txt)|*.txt|SQL 文件 (*.sql)|*.sql"
                                         };
                bool? showDialog = dlg.ShowDialog();
                if (showDialog != null && showDialog.Value)
                {
                    LayoutPanel panel = GetActiveSqlControlPanel();
                    SQLControl sqlcontrol = panel.Content as SQLControl;
                    if (sqlcontrol == null)
                    {
                        MessageBoxHelper.ShowCaption("没有可保存的数据", "提示");
                    }
                    else
                    {
                        sqlcontrol.SaveFile(dlg.FileName);
                        int index = panel.Caption.ToString().IndexOf('*');
                        if (index > 0)
                        {
                            panel.Caption = panel.Caption.ToString().Remove(index);
                        }
                    }
                }

            }, () => {
                LayoutPanel panel = GetActiveSqlControlPanel();
                if (panel != null)
                {
                    SQLControl control = panel.Content as SQLControl;
                    return control != null;
                }
                return false;
            });
            RunCommand = new DelegateCommand(() =>
            {
                LayoutPanel panel = GetActiveSqlControlPanel();
                SQLControl control = panel.Content as SQLControl;
                if (control != null)
                {
                    control.ViewModel.ExecSqlCommand.Execute(control.ViewModel.SelectText);
                }
            }, () => {
                LayoutPanel panel = GetActiveSqlControlPanel();
                if (panel != null)
                {
                    SQLControl control = panel.Content as SQLControl;
                    if (control != null)
                    {
                        if (control.ViewModel != null)
                        {
                            return !string.IsNullOrEmpty(control.ViewModel.SelectText);
                        }
                    }
                }
                return false;
            });
            ClearCommand = new DelegateCommand(() =>
            {
                LayoutPanel panel = GetActiveSqlControlPanel();
                SQLControl control = panel.Content as SQLControl;
                if (control != null)
                {
                    control.Clear();
                }
            }, () => {
                LayoutPanel panel = GetActiveSqlControlPanel();
                if (panel != null)
                {
                    SQLControl control = panel.Content as SQLControl;
                    if (control != null)
                    {
                        return control.IsTxtContent;
                    }
                }
                return false;
            });
            FindCommand = new DelegateCommand(() => { });
            ReplaceCommand = new DelegateCommand(() => { });

            AddDocumentCommand = new DelegateCommand(() => ShowNewWindowLoadFile("新文档" + _documentCount++ + ".txt", "", false));
            AboutCommand = new DelegateCommand(() => {
                AboutWindow about = new AboutWindow();
                about.ShowDialog();
            });
        }

        #region 工具栏

        //编辑数据源
        public void EditDBExecuted(ConnectionModel model)
        {
            RegistDB regist = new RegistDB();
            regist.BindData(model);
            if (regist.ShowDialog() == true)
            {
                this._treeViewModel.Connection();
            }
        }
        //拷贝字段名
        public void CopyFieldNameExecuted()
        {
            this._treeViewModel.CopyCommand.Execute(this._treeViewModel.SelectedItem);
        }
        //格式刷
        public bool TxtFormatCanExecute()
        {
            LayoutPanel panel = GetActiveSqlControlPanel();

            SQLControl control = panel.Content as SQLControl;
            if (control != null)
            {
                if (control.ViewModel != null)
                {
                    return !string.IsNullOrEmpty(control.ViewModel.SelectText);
                }
            }
            return  false;
        }
        public void TxtFormatExecuted()
        {
            LayoutPanel panel = GetActiveSqlControlPanel();
            SQLControl control = panel.Content as SQLControl;
            if (control != null)
            {
                control.ViewModel.SqlFormatPainter(control.ViewModel.SelectText, true);
            }
        }
        //打开文件
        public void FileOpenExecuted()
        {
            OpenFileDialog dlg = new OpenFileDialog
                                     {
                                         ValidateNames = true,
                                         CheckPathExists = true,
                                         CheckFileExists = true,
                                         Filter = "文本文件 （*.txt)|*.txt|SQL 文件 (*.sql)|*.sql"
                                     };
            bool? showDialog = dlg.ShowDialog();
            if (showDialog != null && showDialog.Value)
            {
                ShowNewWindowLoadFile(dlg.SafeFileName, dlg.FileName,true);
            }
        }

        //另存为文件
        public void FileSaveAsExecuted()
        {
            SaveFileDialog dlg = new SaveFileDialog
                                     {
                                         Filter = "文本文件 （*.txt)|*.txt|SQL 文件 (*.sql)|*.sql"
                                     };
            bool? showDialog = dlg.ShowDialog();
            if (showDialog != null && showDialog.Value)
            {
                LayoutPanel panel = GetActiveSqlControlPanel();
                SQLControl sqlcontrol = panel.Content as SQLControl;
                if (sqlcontrol == null)
                {
                    MessageBoxHelper.ShowCaption("没有可保存的数据", "提示");
                }
                else
                {
                    sqlcontrol.SaveFile(dlg.FileName);
                    int index = panel.Caption.ToString().IndexOf('*');
                    if (index > 0)
                    {
                        panel.Caption = panel.Caption.ToString().Remove(index);
                    }
                }
            }
        }
        public bool FileSaveAsCanExecute()
        {
            LayoutPanel panel = GetActiveSqlControlPanel();
            SQLControl control = panel.Content as SQLControl;
            return control != null;
        }
        //运行
        public void RunSqlExecuted()
        {
            LayoutPanel panel = GetActiveSqlControlPanel();
            SQLControl control = panel.Content as SQLControl;
            if (control != null)
            {
                //先保存
                DocumentPanel dp = control.Tag as DocumentPanel;
                if (dp != null && dp.Caption.ToString().IndexOf('*') > 0)
                {
                    string fileName = dp.Caption.ToString().Replace("*", "");
                    if(fileName != "文档")
                    {
                        fileName = AppDomain.CurrentDomain.BaseDirectory +"\\Temporary\\" + fileName;
                    }
                    else
                    {
                        fileName = control.FilePath;
                    }
                    control.SaveFile(fileName);
                    dp.Caption = dp.Caption.ToString().Replace("*", "");
                }
                //再执行
                control.ViewModel.ExecSqlCommand.Execute(control.ViewModel.SelectText);
            }
        }
        public bool RunSqlCanExecute()
        {
            LayoutPanel panel = GetActiveSqlControlPanel();
            if (panel != null)
            {
                SQLControl control = panel.Content as SQLControl;
                if (control != null)
                {
                    if (control.ViewModel != null)
                    {
                        return !string.IsNullOrEmpty(control.ViewModel.SelectText);
                    }
                }
            }
            return false;
        }
        //皮肤
        public void SkinChanged(DependencyObject obj,string themeName)
        {
            ThemeManager.SetThemeName(obj, themeName);
            WriteTheme(themeName);
        }
        #endregion

        #region 命令
        public DelegateCommand CreateDBCommand { get; set; }
        public DelegateCommand TxtFormatCommand { get; set; }
        public DelegateCommand FileOpenCommand { get; set; }
        public DelegateCommand FileSaveCommand { get; set; }
        public DelegateCommand FileSaveAsCommand { get; set; }
        public DelegateCommand RunCommand { get; set; }
        public DelegateCommand ClearCommand { get; set; }
        public DelegateCommand FindCommand { get; set; }
        public DelegateCommand ReplaceCommand { get; set; }
        public DelegateCommand AddDocumentCommand { get; set; }
        public DelegateCommand AboutCommand { get; set; }
        #endregion

        public Action<string, string,bool> ShowNewWindowLoadFile { get; set; }
        public Func<LayoutPanel> GetActiveSqlControlPanel { get; set; }
        public Func<LayoutPanel> GetActiveTableDefinitionControlPanel { get; set; }

        public void ReadTheme(DependencyObject obj)
        {
            string theme = XmlHelper.Instance.ThemeInfo;
            if (!string.IsNullOrEmpty(theme))
            {
                ThemeManager.SetThemeName(obj, theme);
            }
        }
        public void WriteTheme(string theme)
        {
            XmlHelper.Instance.ThemeInfo = theme;
        }
    }
}
